<template>
  <div class="chat-container">
    <!-- 聊天窗口 -->
    <div class="header">
      <h3>与 {{ toUser }} 聊天中</h3>
    </div>

    <!-- 聊天消息窗口 -->
    <div class="chat-window">
      <div v-for="(msg, index) in messages" :key="index"
        :class="['message-row', msg.receiverId !== receiverId ? 'left' : 'right']">
        <div class="message" :class="msg.receiverId !== receiverId ? 'from-other' : 'from-me'">
          <span>{{ msg.content }}</span>
        </div>
      </div>
    </div>



    <!-- 输入框和按钮 -->
    <div class="input-container"  @keyup.enter="sendMessage">
      <textarea v-model="textMessage" placeholder="输入消息..." @focus="isEmojiPickerVisible = false" ></textarea>

      <!-- emoji 表情选择器 -->
      <div v-if="isEmojiPickerVisible" class="emoji-picker-container">
        <!-- <v-emoji-picker @emojiClick="onEmojiClick" /> -->
        <VEmojiPicker @select="onEmojiClick" />
      </div>

      <div class="action-buttons">
        <button @click="toggleEmojiPicker" >😊</button>
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted } from 'vue'
export default {

  data() {
    return {
      ws: null, // WebSocket 实例
      username: localStorage.getItem("username"),     // 当前用户（登录用户）
      toUser: this.$route.query.username,         // 要发送消息的对象（聊天对象）从路由参数获取
      textMessage: '',
      messages: [],
      isEmojiPickerVisible: false, // 控制表情选择器显示与隐藏
      receiverId: this.$route.query.userId
    }
  },
  mounted() {
    this.connectWebSocket()
  },
  methods: {
    connectWebSocket() {
      this.ws = new WebSocket(`ws://localhost:8585/singleChat/${this.username}`)

      this.ws.onopen = () => {
        console.log('WebSocket 连接成功')
      }

      this.ws.onmessage = (event) => {
        const data = event.data
        const [type, content] = data.split('|')
        this.messages.push({ from: this.toUser, content })
      }

      this.ws.onclose = () => {
        console.log('WebSocket 连接关闭')
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket 错误:', error)
      }
    },
    sendMessage() {
      if (!this.textMessage.trim()) return
      const formatted = `${this.toUser}:text:${this.textMessage}`
      this.ws.send(formatted)

      // 假设当前用户是 sender
      this.messages.push({
        senderId: this.username,
        receiverId: this.receiverId,
        content: this.textMessage
      })

      this.textMessage = ''
    },

    onEmojiClick(emoji) {
      this.textMessage += emoji.data
    },
    toggleEmojiPicker() {
      this.isEmojiPickerVisible = !this.isEmojiPickerVisible
    },
    // 获取聊天记录
    getChatHistoryMessage() {
      let url = "/api/im/message/list/" + this.$route.query.userId;
      this.$http.get(url).then((res) => {
        if (res.data.code === 200) {
          this.messages = res.data.data;
          console.log(res.data.data);

        } else {
          console.log("获取聊天记录失败");
        }
      });
    }
  },
  mounted() {
    this.connectWebSocket()
    this.getChatHistoryMessage()
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  max-width: 600px;
  margin: 50px auto;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  overflow: hidden;
}

.header {
  background-color: #4CAF50;
  color: white;
  text-align: center;
  padding: 10px;
  font-size: 20px;
  font-weight: bold;
}

.chat-window {
  height: 300px;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9f9f9;
}

.my-message {
  text-align: right;
  margin-bottom: 10px;
}

.my-message .message {
  background-color: #4CAF50;
  color: white;
  border-radius: 10px;
  padding: 10px;
  max-width: 80%;
  display: inline-block;
  word-wrap: break-word;
}

.other-message {
  text-align: left;
  margin-bottom: 10px;
}

.other-message .message {
  background-color: #f0f0f0;
  color: #333;
  border-radius: 10px;
  padding: 10px;
  max-width: 80%;
  display: inline-block;
  word-wrap: break-word;
}

.input-container {
  padding: 15px;
  border-top: 1px solid #ddd;
  background-color: #f7f7f7;
}

textarea {
  width: 100%;
  height: 60px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  resize: none;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

button {
  padding: 8px 15px;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  background-color: #4CAF50;
  color: white;
  font-size: 16px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

button:active {
  background-color: #388e3c;
}

.emoji-picker-container {
  position: absolute;
  bottom: 80px;
  right: 10px;
  background-color: white;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  z-index: 1000;
}

.chat-window {
  padding: 10px;
}

.message-row {
  display: flex;
  margin: 5px 0;
}

.message-row.left {
  justify-content: flex-start;
  /* 我的消息靠左 */
}

.message-row.right {
  justify-content: flex-end;
  /* 对方消息靠右 */
}

.message {
  max-width: 60%;
  padding: 8px 12px;
  border-radius: 10px;
  background-color: #f1f1f1;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  word-break: break-word;
}

.chat-window {
  padding: 10px;
  max-height: 500px;
  overflow-y: auto;
}

.message-row {
  display: flex;
  margin: 5px 0;
}

.message-row.left {
  justify-content: flex-start;
}

.message-row.right {
  justify-content: flex-end;
}

.message {
  max-width: 60%;
  padding: 10px 15px;
  border-radius: 10px;
  word-break: break-word;
  color: #fff;
}

.message.from-me {
  background-color: #4CAF50;
  /* 绿色 */
}

.message.from-other {
  background-color: #2196F3;
  /* 蓝色 */
}
</style>
